package com.usian.behavior.listener;

import com.alibaba.fastjson.JSON;
import com.usian.behavior.service.ApFollowBehaviorService;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.constants.FollowBehaviorConstants;
import com.usian.model.common.constants.NewsAutoScanConstants;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
  * 功能描述：接受来自kafka的消息
  */
@Component
public class BehaviorKafkaListener {

    @Autowired
    private ApFollowBehaviorService apFollowBehaviorServiceI;


    /**
      * 功能描述：处理关注行为记录的消息
      */
    @KafkaListener(topics = {FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC})
    public void listenNewsScan(ConsumerRecord<?,?> consumerRecord){
        // 优雅地处理null的，避免空指针异常
        Optional<? extends ConsumerRecord<?, ?>> recordOptional = Optional.ofNullable(consumerRecord);
        if (recordOptional.isPresent()) {
            FollowBehaviorDto dto =
                    JSON.parseObject((String) consumerRecord.value(), FollowBehaviorDto.class);
            apFollowBehaviorServiceI.saveFollowBehavior(dto);
        }
    }
}
